<?php require_once(dirname(__FILE__).'/../../func/func_db.php'); ?>
<?php require_once(dirname(__FILE__).'/../../../../../wp-includes/pluggable.php'); ?>
<?php 
	function get_user_role($userid){
		$rolemeta = db_usermeta($userid, 'wp_capabilities');
		$role			= maybe_unserialize($rolemeta->meta_value);
		return $role;
	}
	
	function authority($username, $pwdwords, &$error_key){
		$error_key = null;
		if(empty($username) || empty($pwdwords)){
			$user = null;
			$error_key = 10;
			return $user;
		}
		$user = wp_authenticate($username, decode($pwdwords));
		if (is_wp_error($user)) {
			$user = null;
			$error_key = 11;
		}else{
	//		wp_set_current_user( $user->ID );
	//		echo $user->ID.'-'.$user->user_login;
			//check role and must be 'administrator'
			$role_key		= 'administrator';
			$user_role	= get_user_role($user->ID);
			if(1 != $user_role[$role_key]){
				$user = null;
				$error_key = 12;
			}
		}
			return $user;
	}
	
	//encode the pwd to string.
	function encode($instr, $key){
		$usekey = md5($key);
		$len		= strlen($instr);
		for($i=0; $i<$len; $i++){
			$usekey[31-$i*2] = $instr[$i];
		}
		$usekey[1] = chr($len%6+97);
		$usekey[2] = chr(($len-$len%6)/6+97);
		$outstr = $usekey;
		return $outstr;
	}
	
	//decode the string to pwd.
	function decode($instr){
		$usekey = $instr;
		$len		= (ord($usekey[1])-97)+(ord($usekey[2])-97)*6;
		$outstr	= '';
		for($i=0; $i<$len; $i++){
			$outstr .= $usekey[31-$i*2];
		}
		return $outstr;
	}
	
?>